package cn.seaboot.excel.html;

import cn.seaboot.excel.ExcelStyle;
import cn.seaboot.html.HtmlReader;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFFont;

import java.io.IOException;
import java.io.Writer;

/**
 * 读取单元格的文本样式，转换成 css 写入到输出流中
 * <p>
 * 不支持流式读取的 Wordbook
 *
 * @author Mr.css
 * @version 2025-06-26 14:37
 */
public class StyleReader implements HtmlReader<Workbook> {

    /**
     * 结果写出
     */
    private final Writer writer;

    /**
     * 字体大小偏移量
     * <p>
     * 推荐为 +4，这与屏幕分辨率有关
     */
    public int fontSizeOffset = 4;

    /**
     * 单元格 class 名称前缀
     */
    private String prefix = "td-font-";

    public StyleReader(Writer writer) {
        this.writer = writer;
    }

    public int getFontSizeOffset() {
        return fontSizeOffset;
    }

    public void setFontSizeOffset(int fontSizeOffset) {
        this.fontSizeOffset = fontSizeOffset;
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public void read(Workbook workbook) throws IOException {
        int len = workbook.getNumberOfFonts();
        writer.write("<style>\r\n");
        for (int i = 0; i < len; i++) {
            XSSFFont font = (XSSFFont) workbook.getFontAt(i);

            writer.write("." + prefix + i + "{");

            // 字体大小
            int fontSize = font.getFontHeightInPoints() + fontSizeOffset;
            writer.write("font-size: " + fontSize + "px;");

            // 字体名称
            writer.write("font-family: " + font.getFontName() + ",sans-serif;");

            // 字体颜色
            if (font.getColor() != XSSFFont.DEFAULT_FONT_COLOR) {
                String color = ExcelStyle.convertHexString(font.getXSSFColor());
                writer.write("color: " + color + ";");
            }

            // 字体粗细
            if (font.getBold()) {
                writer.write("font-weight: bold;");
            }

            writer.write("}\r\n");
        }
        writer.write("</style>");
    }
}
